package sistem.management.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sistem.manangement.model.SMUser;
import sistem.manangement.model.UserType;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class SalveazaSecretara extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		SMUser mSecretara = new SMUser();
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

		mSecretara.setFirstName(req.getParameter("prenume"));
		mSecretara.setLastName(req.getParameter("nume"));
		mSecretara.setEmail(req.getParameter("email"));
		mSecretara.setType(UserType.SECRETARA);

		Key secretaraKey = KeyFactory.createKey("user", mSecretara.getEmail());
		Entity secretara = null;
		try {
			secretara = datastore.get(secretaraKey);
			System.out.println("adresa de email deja folosita");
			req.setAttribute("status", "fail");
			resp.setContentType("text");
			resp.setStatus(HttpServletResponse.SC_OK);
			resp.getWriter().write("fail");
		} catch (EntityNotFoundException e) {
			e.printStackTrace();
			System.out.println("Se creaza un cont de secretara");
			secretara = new Entity(secretaraKey);
			secretara.setProperty("nume", mSecretara.getLastName());
			secretara.setProperty("prenume", mSecretara.getFirstName());
			secretara.setProperty("email", mSecretara.getEmail());
			secretara.setProperty("usertype", mSecretara.getType().toString());

			datastore.put(secretara);
			System.out.println("Cont creat cu succes");
			req.setAttribute("status", "succes");
			resp.setContentType("text");
			resp.getWriter().write("succes");
		}

	}

}
